import React, { useState, useContext } from "react";
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Text,
  Platform,
  TextInput,
  Alert,
} from "react-native";

import { AntDesign } from "@expo/vector-icons";
import { Feather } from "@expo/vector-icons";
import { FontAwesome } from "@expo/vector-icons";

import * as Animatable from "react-native-animatable";

import { useDispatch } from "react-redux";
import { signin } from "../../store/actions";
import LoadingBar from "../../components/InterView/LoadingBar";

const SignInScreen = ({ navigation }) => {
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(false);

  const [data, setData] = useState({
    email: "",
    password: "",
    check_textInputChange: false,
    secureTextEntry: true,
    isValidUser: true,
    isValidPassword: true,
  });

  const textInputChange = (val) => {
    // if (val.trim().length >= 4) {
    setData({
      ...data,
      email: val,
      check_textInputChange: true,
      isValidUser: true,
    });
    // } else {
    //   setData({
    //     ...data,
    //     email: val,
    //     check_textInputChange: false,
    //     isValidUser: false,
    //   });
    // }
  };

  const handlePasswordChange = (val) => {
    // setData({ ...data, password: val });
    // if (val.trim().length >= 8) {
    setData({
      ...data,
      password: val,
      check_textInputChange: true,
      isValidPassword: true,
    });
    // } else {
    //   setData({
    //     ...data,
    //     password: val,
    //     check_textInputChange: false,
    //     isValidPassword: false,
    //   });
    // }
  };

  const updateSecureTextEntry = (val) => {
    setData({ ...data, secureTextEntry: !data.secureTextEntry });
  };

  const loginHandler = (userName, password) => {
    if (data.email.length == 0 || data.password.length == 0) {
      Alert.alert("提示", "账号或密码不能为空", [{ text: "确定" }]);
      return;
    }
    dispatch(signin(data.email, data.password, setIsLoading));
  };

  const handleValidUser = (val) => {
    // if (val.trim().length >= 4) {
    setData({
      ...data,
      isValidUser: true,
    });
    // } else {
    //   setData({
    //     ...data,
    //     isValidUser: false,
    //   });
    // }
  };
  return (
    <View style={styles.container}>
      <LoadingBar visible={isLoading} />
      <View style={styles.header}>
        <Text style={styles.text_header}>e 评 估</Text>
      </View>
      <Animatable.View style={styles.footer} animation="fadeInUpBig">
        <Text style={styles.text_footer}>账号</Text>
        <View style={styles.action}>
          <AntDesign name="user" size={20} color="#05375a" />
          <TextInput
            placeholder="请输入账号"
            style={styles.textInput}
            autoCapitalize="none"
            autoCorrect={false}
            onChangeText={(val) => {
              textInputChange(val);
            }}
            onEndEditing={(e) => {
              handleValidUser(e.nativeEvent.text);
            }}
          />
          {data.check_textInputChange ? (
            <Animatable.View animation="bounceIn">
              <Feather name="check-circle" color="green" size={20} />
            </Animatable.View>
          ) : null}
        </View>

        {data.isValidUser ? null : (
          <Animatable.View animation="fadeIn" duration={500}>
            <Text style={styles.errorMsg}>
              Username must be 4 characters long.
            </Text>
          </Animatable.View>
        )}

        <Text style={[styles.text_footer, { marginTop: 35 }]}>密码</Text>
        <View style={styles.action}>
          <FontAwesome name="lock" color="#05375a" size={20} />
          <TextInput
            placeholder="请输入密码"
            style={styles.textInput}
            secureTextEntry={data.secureTextEntry ? true : false}
            autoCapitalize="none"
            autoCorrect={false}
            onChangeText={(val) => handlePasswordChange(val)}
          />
          <TouchableOpacity onPress={updateSecureTextEntry}>
            {data.secureTextEntry ? (
              <Feather name="eye-off" color="gray" size={20} />
            ) : (
              <Feather name="eye" color="gray" size={20} />
            )}
          </TouchableOpacity>
        </View>
        {data.isValidPassword ? null : (
          <Animatable.View animation="fadeIn" duration={500}>
            <Text style={styles.errorMsg}>
              Password must be 8 characters long.
            </Text>
          </Animatable.View>
        )}
        <View
          style={{
            flexDirection: "row",
            justifyContent: "space-between",
            alignContent: "center",
          }}
        >
          <TouchableOpacity
            style={{ paddingVertical: 10 }}
            onPress={() => navigation.navigate("SignUpScreen")}
          >
            <Text style={{ color: "#666", textAlign: "right" }}>注册账号</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={{ paddingVertical: 10 }}
            onPress={() => navigation.navigate("ForgetPasswordScreen")}
          >
            <Text style={{ color: "#666", textAlign: "right" }}>忘记密码</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.button}>
          <TouchableOpacity
            style={styles.signIn}
            onPress={() => {
              loginHandler(data.email, data.password);
            }}
          >
            <Text style={styles.textSignIn}>登 录</Text>
          </TouchableOpacity>
        </View>
      </Animatable.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#780808",
  },
  header: {
    flex: 1,
    justifyContent: "flex-end",
    paddingHorizontal: 20,
    paddingBottom: 50,
  },
  footer: {
    flex: 3,
    backgroundColor: "#fff",
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    paddingHorizontal: 20,
    paddingVertical: 30,
  },
  text_header: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 30,
  },
  text_footer: {
    color: "#05375a",
    fontSize: 16,
  },
  action: {
    flexDirection: "row",
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#f2f2f2",
    paddingBottom: 5,
  },
  actionError: {
    flexDirection: "row",
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#FF0000",
    paddingBottom: 5,
  },
  textInput: {
    flex: 1,
    marginTop: Platform.OS === "ios" ? 0 : -12,
    paddingLeft: 10,
    color: "#05375a",
  },
  errorMsg: {
    color: "#FF0000",
    fontSize: 14,
  },
  button: {
    alignItems: "center",
    marginTop: 10,
  },
  signIn: {
    backgroundColor: "#A80108",
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
  },
  signUp: {
    borderColor: "#A80108",
    borderWidth: 1,
    marginTop: 15,
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
  },
  textSignIn: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#fff",
  },
  textSignUp: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#05375a",
  },
});

export default SignInScreen;
